"""
题目：给定单链表头节点和一个新值，在链表末尾添加一个值为新值的节点，返回添加后的链表头节点。
"""


class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next


def append_node(head, new_val):
    """在链表末尾添加值为new_val的新节点"""
    # 步骤1：创建新节点
    new_node = ListNode(new_val)

    # 步骤2：处理空链表情况（头节点为None）
    if not head:
        return new_node  # 新节点成为头节点

    # 步骤3：遍历到链表末尾
    current = head
    # 找到最后一个节点（next为None的节点）
    while current.next:
        current = current.next

    # 步骤4：将新节点连接到末尾
    current.next = new_node

    return head


def create_linked_list(arr):
    if not arr:
        return None
    head = ListNode(arr[0])
    current = head
    for val in arr[1:]:
        current.next = ListNode(val)
        current = current.next
    return head


def traverse_linked_list(head):
    result = []
    current = head
    while current:
        result.append(current.val)
        current = current.next
    return result


# 测试
if __name__ == "__main__":
    # 测试1：非空链表添加
    head1 = create_linked_list([1, 2, 3])
    new_head1 = append_node(head1, 4)
    print(traverse_linked_list(new_head1))  # 输出: [1, 2, 3, 4]

    # 测试2：空链表添加
    head2 = create_linked_list([])
    new_head2 = append_node(head2, 0)
    print(traverse_linked_list(new_head2))  # 输出: [0]

    # 测试3：单节点链表添加
    head3 = create_linked_list([5])
    new_head3 = append_node(head3, 6)
    print(traverse_linked_list(new_head3))  # 输出: [5, 6]